import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";

import React from "react";

import { addon, log, getObject, Ref } from "pao-aop";
import { ProductClassify, IProductClassifyService, ProductClassifyCondition } from "src/models/productClassify";
import NTDivStyle from "src/business/style-components/div-style";
import FormCreator, { InputType } from "src/business/components/form-creator";
import { GetFieldDecoratorOptions, FormProps } from "antd/lib/form/Form";
import { UPLOAD_URL, beforeUpload, PRODUCT_CLASSIFY_ID, ROUTE_PATH } from "../../app/util-tool";
import { message, Modal } from "antd";
import { NTOperationTable } from "src/business/components/operation-table";
import { DataObject } from "src/business/components/button-alert";

// /** 获取表单props属性 */
let formProps: any;
/**
 * 组件：产品分类编辑视图状态
 */
export interface ChangeProductClassifyViewState extends ReactViewState {
    /** 产品分类数据源 */
    data?: ProductClassify;
    /** 是否显示产品分类选择框 */
    visible?: boolean;
    /** 滚动条 */
    loading?: boolean;
    /** 产品分类modal显示判断 */
    product_classify_visible?: boolean;
    /** 产品分类列表数据源 */
    data_source?: ProductClassify[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 选中产品分类数据集合 */
    product_classify_value?: any;
}

/**
 * 组件：产品分类编辑视图
 * 描述
 */
export class ChangeProductClassifyView extends ReactView<ChangeProductClassifyViewControl, ChangeProductClassifyViewState> {
    private columns_data_source = [{
        title: '名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500
    }, {
        title: '类型',
        dataIndex: 'handle_type',
        key: 'handle_type',
        width: 200,
        render: (text: string, record: any, index: any) => {
            if (text === 'company') {
                return '企业标识';
            } else {
                return '产品分类';
            }
        }
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    constructor(props: ChangeProductClassifyViewControl) {
        super(props);
        this.state = {
            data: {}
        };
    }
    /** 返回按钮 */
    onClickBack = () => {
        this.props.history!.push(ROUTE_PATH.productClassify);
    }
    /** 提交按钮 */
    onClickSubmit = (e: any, data: ProductClassify) => {
        this.setState({
            loading: true
        });
        let { [PRODUCT_CLASSIFY_ID]: id } = this.props.match!.params;
        if (id) {
            data.id = id;
        }
        data.handle_type = 'classify';
        this.saveData(data!)
            .then(() => {
                this.setState({
                    loading: false
                });
                message.info("保存成功");
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("insert_product_classify", error.message);
                message.info('保存失败：' + error.message);
            });
    }
    // 保存服务调用
    async saveData(data: ProductClassify) {
        await this.productClassifyService!()!.insert!(data)!;
        this.props.history!.push(ROUTE_PATH.productClassify);
    }
    // 查询详情信息
    async queryData(id: string) {
        const data = await this.productClassifyService!()!.get_product_classify!(id)!;
        return data;
    }

    // 初始化服务
    productClassifyService?() {
        return getObject(this.props.productClassifyService_Fac!);
    }
    componentDidMount() {
        let condition: ProductClassifyCondition = {};
        this.queryList(condition, 1, 10)
            .then((res) => {
                this.setState({
                    loading: false,
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("productClassifyViewControl", error.message);
            });

    }
    // 查询列表信息
    async queryList(condition: ProductClassifyCondition, page: number, count: number) {
        const data = await this.productClassifyService!()!.get_parent_list!(condition, page, count)!;
        // let parent_id;
        let parent_id: any = {};
        let { [PRODUCT_CLASSIFY_ID]: id } = this.props.match!.params;
        if (id) {
            this.setState({
                loading: true
            });
            parent_id = await this.queryData(id);
        }
        // let res = {
        //     parent_id: parent_id
        // };
        this.setState({
            data: parent_id,
            total_data: data ? data!.total : 0, // 应当取接口返回的总数
            data_source: data ? data!.result : [],
            loading: false,
        });
    }
    /**
     * 引用产品分类按钮方法
     */
    select_parent = () => {
        this.setState({
            // stencil_value: [],
            product_classify_visible: true
        });
    }

    /** 产品分类选择框确定回调方法 */
    handleOk = () => {
        // 把已经选中的自定义属性列表放入data中
        let data = this.state.data;
        // data!.custom_attribute = this.state.product_classify_value!;
        console.log('最终值', this.state.product_classify_value);
        this.setState({
            product_classify_visible: false,
            data
        });
        // 设置自定义控件的值
        formProps.setFieldsValue({
            custom_attribute: data!.custom_attribute,
            parent_id: this.state.product_classify_value.id ? this.state.product_classify_value.id : ''
        });
    }

    /** 产品分类选择框取消回调方法 */
    handleCancel = (e: any) => {
        this.setState({
            product_classify_visible: false,
        });
    }
    /** 行选中回调 */
    private handleRowSelect = (e: ProductClassify[]) => {
        let value: ProductClassify = {};
        if (e.length > 0) {
            value = e[0];
        }
        this.setState({
            product_classify_value: value,
        });
    }
    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList({}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("productClassifyViewControl-pageOnCick", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList({}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("productClassifyViewControl-showSizeChange", error.message);
            });
    }
    render() {
        let { data } = this.state;
        /** 产品类型select框 */
        // 父级选择框数据源
        let button_alert_data: DataObject[] = [];
        let source = this.state.data_source;
        if (source) {
            for (let i = 0; i < source!.length; i++) {
                button_alert_data.push({ id: source[i].id, name: source[i].handle_name });
            }
        }
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
        };
        let edit_props = {
            loading: this.state.loading,
            form_props: {
                hideRequiredMark: true
            } as FormProps,
            form_items_props: [
                {
                    title: "产品分类设置",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.input,
                            label: "产品分类名称",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入产品分类名称" }],
                                initialValue: data && data!.handle_name ? data!.handle_name : '',
                            } as GetFieldDecoratorOptions,
                            decorator_id: "handle_name"
                        },
                        {
                            type: InputType.button_alert,
                            label: "上级分类",
                            decorator_id: "parent_id",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请选择产品分类" }],
                                initialValue: data!.parent_id ? data!.parent_id : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                button_name: '选择分类',
                                onClick: this.select_parent,
                                alert_type: "success",
                                data: button_alert_data
                            }
                        },
                        {
                            type: InputType.customProperties,
                            label: "产品分类内容",
                            decorator_id: "custom_attribute",
                            field_decorator_option: {
                                // rules: [{ required: true, message: "请设置产品分类" }],
                                initialValue: data!.custom_attribute
                            } as GetFieldDecoratorOptions,
                            option: {
                                befor_placeholder: '类目名称',
                                after_placeholder: '请输入类目信息',
                                type_key: 'format',
                                before_key: 'label',
                                after_key: 'value',
                                upload_action: UPLOAD_URL,
                                upload_amount: 5,
                                beforeUpload: beforeUpload
                            }
                        }
                    ]
                }],
            form_item_layout: formItemLayout,
            row_btn_props: {
                style: {
                    justifyContent: " center"
                }
            },
            other_btn_propps: [
                {
                    text: "返回",
                    cb: this.onClickBack
                }
            ],
            submit_btn_propps: {
                text: "保存",
                cb: this.onClickSubmit
            }
        };
        return (
            <NTDivStyle.NTDefaultDiv>
                <Modal
                    title="请选择产品分类！"
                    visible={this.state.product_classify_visible}
                    onOk={() => this.handleOk()}
                    onCancel={this.handleCancel}
                >
                    <NTOperationTable
                        data_source={this.state.data_source}
                        columns_data_source={this.columns_data_source}
                        on_row_selection={this.handleRowSelect}
                        type='radio'
                        table_size='middle'
                        showHeader={true}
                        bordered={true}
                        total={this.state.total_data}
                        default_page_size={10}
                        total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 0) / 10)}
                        show_footer={true}
                        page_on_click={this.pageOnCick}
                        show_size_change={this.showSizeChange}
                    />
                </Modal>
                <FormCreator {...edit_props} ref={(e: any) => formProps = e} />
            </NTDivStyle.NTDefaultDiv>
        );
    }
}

/**
 * 控件：产品分类编辑视图
 * 描述
 */
@addon('ChangeProductClassifyView', '产品分类编辑视图', '描述')
@reactControl(ChangeProductClassifyView, true)
export class ChangeProductClassifyViewControl extends ReactViewControl {
    /**
     * 产品分类服务
     */
    public productClassifyService_Fac?: Ref<IProductClassifyService>;
}